package com.common.函数类应用转换源;

import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 单向转换
 * @param <Source> 转换源
 * @param  <Target> 目标类
 * @author glz
 * @date 2019/6/11
 */
public abstract class OneWayConverter<Source,Target> implements Convert<Source,Target>{
    /**
     * 转换至目标类的Function
     */
    protected final Function<Source,Target> convertToTarget;

    public OneWayConverter(Function<Source, Target> convertToTarget) {
        this.convertToTarget = convertToTarget;
    }

    /**
     * 把Source类转换成Target类
     * @param source 转换源
     * @return 目标类(若源类为空,返回null)
     */
    public final Target convertToTargetClass(Source source){
        if (source == null){
            return null;
        }
        return convertToTarget.apply(source);
    }

    /**
     * 集合转换
     * @param sourceList 源类集合
     * @return 目标类集合(若源类集合为空返回null)
     */
    public final List<Target> convertToTargetClass(List<Source> sourceList) {
        if (CollectionUtils.isEmpty(sourceList)){
            return null;
        }
        return sourceList.stream().map(this::convertToTargetClass).collect(Collectors.toList());
    }


}